#!/bin/sh

UPDATE_SYSTEM_STATUS_SUCCESS=/tmp/.update_system_success
UPDATE_SYSTEM_STATUS_FAIL=/tmp/.update_system_fail
UPDATE_SYSTEM_STATUS_ING=/tmp/.update_system_ing

TARGET_PACKAGE=$1

WORK_STATION=/tmp/update_station/system/
zip_pwd=tz18c6


go_exit()
{
	rm ${UPDATE_SYSTEM_STATUS_ING} -f
	if [ "$1" = "success" ]; then
		rm ${UPDATE_SYSTEM_STATUS_FAIL} -f
		touch ${UPDATE_SYSTEM_STATUS_SUCCESS}
	else
		rm ${UPDATE_SYSTEM_STATUS_SUCCESS} -f
		touch ${UPDATE_SYSTEM_STATUS_FAIL}
	fi
	exit
}


touch ${UPDATE_SYSTEM_STATUS_ING}

if [ "${TARGET_PACKAGE}" = "" -o ! -f ${TARGET_PACKAGE} ]; then
	echo "the target package is not exist"
	go_exit
fi

mkdir -p ${WORK_STATION}
rm -rf ${WORK_STATION}/*

#解压到升级目录
unzip -P ${zip_pwd} ${TARGET_PACKAGE} -d ${WORK_STATION}

#追加配置处理
cd ${WORK_STATION}
append_config_file_exist=`ls ConfigUpdateAppend/*.conf | wc -l`
if [ "${append_config_file_exist}" = "1" ]; then
	mkdir -p /etc/config_update_file
	cp ConfigUpdateAppend/*.conf /etc/config_update_file/updateconfig.conf
	sync
fi

#LOGO处理
cd ${WORK_STATION}
logo_exist=`ls LOGO/*.gif | wc -l`
if [ "${logo_exist}" = "1" ]; then
	cp LOGO/*.gif /tz_www/images/customer.gif -rf
	sync
fi

#check modem update
cd ${WORK_STATION}
modem_update_result=0

modem_bin=`ls ModemUpdate/ | grep .bin 2>/dev/null`
if [ "${modem_bin}" != "" ]; then
	/etc/init.d/dialtool2 stop
	adb push ${WORK_STATION}/ModemUpdate/${modem_bin} /cache/firmware.bin
	tmp_result=$?
	if [ "${tmp_result}" == "0" ]; then
		echo ">>>>>>>>>>>1"
		tmp_result=`sendat -e "at+bmcmd=UPGRADE,/cache/firmware.bin,1" | grep +BMCMD-UPGRADE | awk '{print $2}'`
		echo "ret= ${tmp_result}"
		if [ "${tmp_result}" == "OK" ]; then
			echo ">>>>>>>>>>>2"
			sleep 40
			tmp_result=`sendat -e "at+bmcmd=BMFTPST" | grep "60" | wc -l`
			echo "ret= ${tmp_result}"
			if [ "${tmp_result}" == "1" ]; then
				echo ">>>>>>>>>>>3"
				sendat -e "at+bmcmd=SWITCH_BACKUP_BOOT"
				sleep 50
				tmp_result=`sendat -e "at+bmcmd=BMFTPST" | grep "90" | wc -l`
				echo "ret= ${tmp_result}"
				if [ "${tmp_result}" == "1" ]; then
					echo ">>>>>>>>>>>4"
					modem_update_result=1
				fi
			fi
		fi
		

	fi
fi

if [ "${modem_update_result}" == "1" ]; then
	echo "modem update success"
else
	echo "modem update fail"
fi

#check firmware md5sum
cd ${WORK_STATION}
if [ ! -f md5sum.txt ]; then
	go_exit
fi

md5_value_in_file=`cat md5sum.txt | awk '{print $1}'` 

system_firmware=`ls | grep firmware | grep bin`

md5_value_by_cal=`md5sum ${system_firmware} | awk '{print $1}'`

if [ "${md5_value_in_file}" != "${md5_value_by_cal}" ]; then
	echo "md5sum fail"
	go_exit
fi

echo "md5sum success"

##firmware update
sysupgrade ${WORK_STATION}/${system_firmware}


